<?php

namespace Modules\Asset\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Asset\Entities\Resale;

use Modules\Asset\Entities\ResaleOrder;

use Validator;
use ThrowException;
use Auth;
use Setting;
use DB;
use Cache;

// 已开出物品
class ResaleOrderController extends Controller
{
    // 提交
    public function confirm(Request $req)
    {
        $rule = [
            'resale_id' => ['required'],
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();

        // 转售
        $resale = Resale::getEntity([
            'id' => $req->resale_id
        ]);

        $cacheKey = 'forzen_resale_' . $resale->id;

        if (Cache::get($cacheKey)) {
            ThrowException::Conflict('此转售被锁定10秒，请稍后再试~');
        }

        if ($resale->user_id === $user->id) {
            ThrowException::Conflict('不能购买自己转售的商品~');
        }

        if ($resale->union_status === 'completed') {
            ThrowException::Conflict('此商品已被买走啦~');
        }

        if ($resale->union_status === 'closed') {
            ThrowException::Conflict('此转售已关闭~');
        }

        if ($resale->union_status !== 'pending') {
            ThrowException::Conflict('此转售暂不可交易~');
        }

        // 运费
        $carriage = 0;

        // 虚拟资产订单发放
        $skuableMaps = [
            [
                'skuable' => $resale,
                'total' => 1
            ]
        ];

        DB::beginTransaction();
        
        $order = ResaleOrder::initWith($skuableMaps, $user, NULL, [
            'options' => [
                'resale_id' => $resale->id
            ]
        ]);

        // 商品转售中
        $resale->update([
            // 'pending_at' => now(),
            'buyer_id'  => $user->id,
            // 'status' => 5
        ]);
   
        $order->createAll();

        DB::commit();

        Cache::put($cacheKey, 1, 10);

        return $order->generateResponse();
    }
}
